package com.party.business.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.party.business.domain.*;
import com.party.business.mapper.TQuestionMapper;
import com.party.business.mapper.TQuestionOptionMapper;
import com.party.business.service.ITQuestionOptionService;
import com.party.business.service.ITQuestionService;
import com.party.business.service.ITQuestionTypeService;
import com.party.common.core.domain.entity.SysUser;
import com.party.common.exception.ServiceException;
import com.party.common.utils.DateUtils;
import com.party.common.utils.SecurityUtils;
import com.party.common.utils.StringUtils;
import com.party.common.utils.bean.BeanValidators;
import io.jsonwebtoken.lang.Collections;
import org.aspectj.weaver.patterns.TypePatternQuestions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * 试题信息Service业务层处理
 *
 * @author ruoyi
 * @date 2024-11-08
 */
@Service
public class TQuestionServiceImpl extends ServiceImpl<TQuestionMapper, TQuestion> implements ITQuestionService {
    @Autowired
    private TQuestionMapper tQuestionMapper;

    @Autowired
    private TQuestionOptionMapper questionOptionMapper;

    @Autowired
    private ITQuestionOptionService questionOptionService;

    /**
     * 查询试题信息
     *
     * @param id 试题信息主键
     * @return 试题信息
     */
    @Override
    public TQuestion selectTQuestionById(String id) {
        TQuestion tQuestion = tQuestionMapper.selectTQuestionById(id);
        TQuestionOption oldoption = new TQuestionOption();
        oldoption.setQuId(id);
        // 数据库旧的选项
        List<TQuestionOption> oldoptionList = questionOptionMapper.selectTQuestionOptionList(oldoption);
        tQuestion.setOptionList(oldoptionList);
        return tQuestion;
    }

    /**
     * 查询试题信息列表
     *
     * @param tQuestion 试题信息
     * @return 试题信息
     */
    @Override
    public List<TQuestion> selectTQuestionList(TQuestion tQuestion) {
        return tQuestionMapper.selectTQuestionList(tQuestion);
    }

    /**
     * 新增试题信息
     *
     * @param tQuestion 试题信息
     * @return 结果
     */
    @Override
    public int insertTQuestion(TQuestion tQuestion) {
        tQuestion.setCreateTime(DateUtils.getNowDate());
        return tQuestionMapper.insertTQuestion(tQuestion);
    }

    /**
     * 修改试题信息
     *
     * @param tQuestion 试题信息
     * @return 结果
     */
    @Override
    public int updateTQuestion(TQuestion tQuestion) {
        tQuestion.setUpdateTime(DateUtils.getNowDate());
        return tQuestionMapper.updateTQuestion(tQuestion);
    }

    /**
     * 批量删除试题信息
     *
     * @param ids 需要删除的试题信息主键
     * @return 结果
     */
    @Override
    public int deleteTQuestionByIds(String[] ids) {
        return tQuestionMapper.deleteTQuestionByIds(ids);
    }

    /**
     * 删除试题信息信息
     *
     * @param id 试题信息主键
     * @return 结果
     */
    @Override
    public int deleteTQuestionById(String id) {
        return tQuestionMapper.deleteTQuestionById(id);
    }


    @Override
    public void saveQuestion(TQuestion tQuestion) {
        this.save(tQuestion);
        List<TQuestionOption> optionList = tQuestion.getOptionList();
        if (CollectionUtil.isEmpty(optionList)) {
            throw new RuntimeException("请添加选项");
        }
        String quType = tQuestion.getQuType();
        if (quType.equals("1")) {
            boolean isempty = optionList.stream().anyMatch(item -> StringUtils.isEmpty(item.getTitle()));
            if (isempty) {
                throw new RuntimeException("选项内容不能为空");
            }
        }
        // 判断有没有设置正确选项 stream 流 过滤 判断有没有设置正确选项
        boolean isRight = optionList.stream().anyMatch(item -> "true".equals(item.getIsRight()));
        if (!isRight) {
            throw new RuntimeException("请设置正确选项");
        }

        for (int i = 0; i < optionList.size(); i++) {
            TQuestionOption tQuestionOption = optionList.get(i);
            tQuestionOption.setQuId(tQuestion.getId());
            tQuestionOption.setOrderNum(Long.valueOf(i));
            questionOptionService.save(tQuestionOption);
        }

    }

    @Override
    public void updateQuestion(TQuestion tQuestion) {
        this.updateById(tQuestion);
        String questionId = tQuestion.getId();
        TQuestionOption oldoption = new TQuestionOption();
        oldoption.setQuId(questionId);
        // 数据库旧的选项
        List<TQuestionOption> oldoptionList = questionOptionMapper.selectTQuestionOptionList(oldoption);
        // 新选项
        List<TQuestionOption> newoptionList = tQuestion.getOptionList();
        if (Collections.isEmpty(newoptionList)) {
            throw new RuntimeException("请添加选项");
        }
        // 判断有没有设置正确选项 stream 流 过滤 判断有没有设置正确选项
        boolean isRight = newoptionList.stream().anyMatch(item -> "true".equals(item.getIsRight()));
        if (!isRight) {
            throw new RuntimeException("请设置正确选项");
        }
        if (!Collections.isEmpty(newoptionList)) {
            // 删除新数据不存在的旧数据 stream 流
            List<TQuestionOption> filteredNewOptionList = newoptionList.stream()
                    .filter(item2 -> item2.getId() != null)
                    .collect(Collectors.toList());

            oldoptionList.stream().
                    filter(item -> filteredNewOptionList.stream()
                            .noneMatch(item2 ->
                                    item2.getId().equals(item.getId()))).forEach(item ->
                            questionOptionService.removeById(item.getId()));
        }
        for (int i = 0; i < newoptionList.size(); i++) {
            TQuestionOption tQuestionOption = newoptionList.get(i);
            tQuestionOption.setQuId(questionId);
            tQuestionOption.setOrderNum(Long.valueOf(i));
            questionOptionService.saveOrUpdate(tQuestionOption);

        }


    }

    @Autowired
    private ITQuestionTypeService questionTypeService;

    @Override
    @Transactional
    public String importQuestion(List<TQuestionDxDTO> quList, String operName) {
        if (StringUtils.isNull(quList) || quList.size() == 0) {
            throw new ServiceException("导入试题数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        // 查询所有的试题分类的二级
        List<TQuestionType> questionTypeList = questionTypeService.selectTQuestionTypeList(new TQuestionType());
        // 过滤出 parentId 为 不为0 的分类
        List<TQuestionType> secondLevelQuestionTypeList = questionTypeList.stream().filter(item -> item.getParentId() != "0").collect(Collectors.toList());
        for (TQuestionDxDTO qustiondto : quList) {
            try {
                if (StringUtils.isNull(qustiondto.getTitle())) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "标题不能为空");
                }

                TQuestion question = new TQuestion();
                question.setQuType("1");
                question.setTitle(qustiondto.getTitle().trim());
                question.setContent(qustiondto.getContent().trim());
                if (!StringUtils.isNull(qustiondto.getTypeName())) {
                    // 通过分类名称查询分类id secondLevelQuestionTypeList
                    TQuestionType questionType = secondLevelQuestionTypeList.stream().filter(item -> item.getName().equals(qustiondto.getTypeName().trim())).findFirst().orElse(null);
                    question.setType(questionType == null ? "" : questionType.getId());
                }
                this.save(question);
                List<TQuestionOption> optionList = new ArrayList<>();
                String isRight = qustiondto.getIsRight();
                String option1 = qustiondto.getOption1();
                String option2 = qustiondto.getOption2();
                String option3 = qustiondto.getOption3();
                String option4 = qustiondto.getOption4();
                if (StringUtils.isNotEmpty(option1)) {
                    TQuestionOption option = new TQuestionOption();
                    option.setTitle(option1);
                    option.setOptions("A");
                    if (isRight.equals("1")) {
                        option.setIsRight("true");
                    }
                    optionList.add(option);
                }
                if (StringUtils.isNotEmpty(option2)) {
                    TQuestionOption option = new TQuestionOption();
                    option.setTitle(option2);
                    option.setOptions("B");
                    if (isRight.equals("2")) {
                        option.setIsRight("true");
                    }
                    optionList.add(option);
                }
                if (StringUtils.isNotEmpty(option3)) {
                    TQuestionOption option = new TQuestionOption();
                    option.setTitle(option3);
                    option.setOptions("C");
                    if (isRight.equals("3")) {
                        option.setIsRight("true");
                    }
                    optionList.add(option);
                }
                if (StringUtils.isNotEmpty(option4)) {
                    TQuestionOption option = new TQuestionOption();
                    option.setTitle(option4);
                    option.setOptions("D");
                    if (isRight.equals("4")) {
                        option.setIsRight("true");
                    }
                    optionList.add(option);
                }

                if (!CollectionUtil.isEmpty(optionList)) {
                    for (int i = 0; i < optionList.size(); i++) {
                        TQuestionOption tQuestionOption = optionList.get(i);
                        tQuestionOption.setQuId(question.getId());
                        tQuestionOption.setOrderNum(Long.valueOf(i));
                        questionOptionService.save(tQuestionOption);
                    }
                }
                successNum++;

            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }


    @Override
    @Transactional
    public String importPdQuestion(List<TQuestionPdDTO> quList, String operName) {
        if (StringUtils.isNull(quList) || quList.size() == 0) {
            throw new ServiceException("导入试题数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        // 查询所有的试题分类的二级
        List<TQuestionType> questionTypeList = questionTypeService.selectTQuestionTypeList(new TQuestionType());
        // 过滤出 parentId 为 不为0 的分类
        List<TQuestionType> secondLevelQuestionTypeList = questionTypeList.stream().filter(item -> item.getParentId() != "0").collect(Collectors.toList());
        for (TQuestionPdDTO qustiondto : quList) {
            try {
                if (StringUtils.isNull(qustiondto.getTitle())) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "标题不能为空");
                }

                TQuestion question = new TQuestion();
                question.setQuType("2");
                question.setTitle(qustiondto.getTitle().trim());
                question.setContent(qustiondto.getContent().trim());
                if (!StringUtils.isNull(qustiondto.getTypeName())) {
                    // 通过分类名称查询分类id secondLevelQuestionTypeList
                    TQuestionType questionType = secondLevelQuestionTypeList.stream().filter(item -> item.getName().equals(qustiondto.getTypeName().trim())).findFirst().orElse(null);
                    question.setType(questionType == null ? "" : questionType.getId());
                }
                this.save(question);
                List<TQuestionOption> optionList = new ArrayList<>();
                String isRight = qustiondto.getIsRight();
                TQuestionOption option1 = new TQuestionOption();
                option1.setTitle("");
                option1.setOptions("对");
                if ("对".equals(isRight)) {
                    option1.setIsRight("true");
                } else {
                    option1.setIsRight("false");
                }
                optionList.add(option1);
                TQuestionOption option2 = new TQuestionOption();
                option2.setTitle("");
                option2.setOptions("错");
                if (option1.getIsRight().equals("true")) {
                    option2.setIsRight("false");
                } else {
                    option2.setIsRight("true");
                }
                optionList.add(option2);
                if (!CollectionUtil.isEmpty(optionList)) {
                    for (int i = 0; i < optionList.size(); i++) {
                        TQuestionOption tQuestionOption = optionList.get(i);
                        tQuestionOption.setQuId(question.getId());
                        tQuestionOption.setOrderNum(Long.valueOf(i));
                        questionOptionService.save(tQuestionOption);
                    }
                }
                successNum++;

            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
